package com.zhijiaoyun.common.email;

import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.Properties;

import javax.mail.Authenticator;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

/**
 * @author shisfish
 * @date 2017/6/6
 */
public class EmailUtils {
	public static String SEND_NAME = "职教云";

	public static String SEND_AUTH_CODE = "ojxlwwbwvaqnjdgj";
	public static String SEND_ACCOUNT = "1119078870@qq.com";
	public static String SEND_PASSWORD = "pssshsdmm1598753";

	public static String SMTP_HOST_163 = "smtp.163.com";
	public static String SMTP_HOST_QQ = "smtp.qq.com";

	private static final String SMTP_PORT = "465";

	

	public static MimeMessage createMimeMessage(Session session, String receiveEmail, String content)
			throws UnsupportedEncodingException, MessagingException {
		// 创建邮件
		MimeMessage message = new MimeMessage(session);
		// From
		message.setFrom(new InternetAddress(SEND_ACCOUNT, SEND_NAME, "UTF-8"));
		// TO
		message.setRecipient(MimeMessage.RecipientType.TO, new InternetAddress(receiveEmail, "我", "UTF-8"));
		// subject
		message.setSubject(SEND_NAME, "UTF-8");
		// content
		message.setContent(content, "text/html;charset=UTF-8");
		// sendDate
		message.setSentDate(new Date());
		// saveChange()
		message.saveChanges();

		return message;
	}

	public static void sendEmail(String receiveEmail, String content) throws Exception {
		// 连接邮件服务器的参数配置
		Properties props = new Properties();
		props.setProperty("mail.transport.protocol", "smtp");
		props.setProperty("mail.smtp.host", SMTP_HOST_QQ);
		props.setProperty("mail.smtp.auth", "true");
		props.setProperty("mail.smtp.port", SMTP_PORT);
		props.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
		props.setProperty("mail.smtp.socketFactory.fallback", "true");
		props.setProperty("mail.smtp.socketFactory.port", SMTP_PORT);

		Authenticator auth = new Authenticator() {
			@Override
			protected PasswordAuthentication getPasswordAuthentication() {
				return new PasswordAuthentication(SEND_ACCOUNT, SEND_AUTH_CODE);
			}
		};

		// 创建会话对象，用于和邮件服务器交互
		Session session = Session.getDefaultInstance(props, auth);
		// 设置成debug，可以查看详细的log
		session.setDebug(true);
		// 根据session获取邮件传输对象
		Transport transport = session.getTransport();
		transport.connect(SEND_ACCOUNT, SEND_PASSWORD);
		// 创建邮箱
		MimeMessage message = createMimeMessage(session, receiveEmail, content);
		transport.sendMessage(message, message.getAllRecipients());
		transport.close();
	}

}
